const app = getApp()
const mockData = require('../../utils/data.js')

Page({
  data: {
    products: [],
    travelers: [],
    booker: {
      name: '',
      phone: '',
      email: '',
      notes: ''
    },
    totalPrice: 0,
    paymentMethod: '微信支付'
  },
  
  onLoad(options) {
    // 从购物车或产品详情页进入
    if (options.productId) {
      // 从产品详情页进入
      const product = mockData.products.find(p => p.id === parseInt(options.productId)) || mockData.products[0]
      this.setData({
        products: [{
          ...product,
          date: options.packageId || '2019-06-19',
          adultCount: 1,
          childCount: 1,
          roomCount: 1
        }],
        totalPrice: product.price
      })
    } else {
      // 从购物车进入
      const selectedItems = app.globalData.cart.filter(item => item.selected)
      const products = selectedItems.map(item => {
        const product = mockData.products.find(p => p.id === item.id) || mockData.products[0]
        return {
          ...product,
          ...item
        }
      })
      
      const totalPrice = products.reduce((sum, item) => sum + (item.price * item.quantity), 0)
      
      this.setData({
        products,
        totalPrice
      })
    }
    
    // 加载常用联系人
    this.loadTravelers()
  },
  
  loadTravelers() {
    // 从本地存储加载常用联系人
    const contacts = wx.getStorageSync('contacts') || []
    this.setData({
      travelers: contacts.slice(0, 2) // 只显示前两个
    })
  },
  
  addTraveler() {
    wx.navigateTo({
      url: '/pages/add-traveler/add-traveler'
    })
  },
  
  editTraveler(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/pages/add-traveler/add-traveler?index=${index}`
    })
  },
  
  deleteTraveler(e) {
    const index = e.currentTarget.dataset.index
    const travelers = this.data.travelers
    travelers.splice(index, 1)
    this.setData({ travelers })
  },
  
  onBookerInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({
      [`booker.${field}`]: e.detail.value
    })
  },
  
  submitOrder() {
    // 验证信息
    if (this.data.travelers.length === 0) {
      wx.showToast({
        title: '请添加出行人',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.booker.name || !this.data.booker.phone) {
      wx.showToast({
        title: '请填写预订人信息',
        icon: 'none'
      })
      return
    }
    
    // 创建订单
    const now = new Date()
    const order = {
      id: Date.now(),
      products: this.data.products,
      travelers: this.data.travelers,
      booker: this.data.booker,
      totalPrice: this.data.totalPrice,
      paymentMethod: this.data.paymentMethod,
      status: 'pending',
      createTime: `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`,
      orderNumber: String(Date.now())
    }
    
    // 保存订单
    const orders = app.globalData.orders || []
    orders.unshift(order)
    app.globalData.orders = orders
    wx.setStorageSync('orders', orders)
    
    // 清空购物车中已选商品
    const cart = app.globalData.cart || []
    app.globalData.cart = cart.filter(item => !item.selected)
    wx.setStorageSync('cart', app.globalData.cart)
    
    // 跳转到订单详情
    wx.redirectTo({
      url: `/pages/order-detail/order-detail?id=${order.id}&status=pending`
    })
  }
})

